
#include "OLDialogSurface.h"
#include "OLDialog.h"
#include "OLAppTemplateDefs.h"
#include "OLDialogTitle.h"

#include <QVBoxLayout>
#include <QParallelAnimationGroup>
#include <QPropertyAnimation>
#include <QDebug>

OLDialogSurface::OLDialogSurface(const QPixmap& icon, const QString& title, QLayout* body, const OLButtonList& buttons, QWidget *parent) :
    OLModalBackground(parent), m_anim(0), m_dialog(0)
{
    OLDialogTitle* dialogTitle = new OLDialogTitle(icon, title, this);
    connect(dialogTitle, SIGNAL(dismissDialog()), SLOT(dismissDialog()));
    m_dialog = new OLDialog(dialogTitle, body, buttons, this);
    connect(m_dialog, SIGNAL(dismissDialog()), SLOT(dismissDialog()));

    connect(this, SIGNAL(portraitSwitch()), m_dialog, (SLOT(handlePortrait())));
    connect(this, SIGNAL(landscapeSwitch()), m_dialog, (SLOT(handleLandscape())));
}

void OLDialogSurface::resizeEvent(QResizeEvent *)
{
    m_dialog->resize(size());
}

void OLDialogSurface::handleParentResize()
{
    resize(parentWidget()->size());
}

void OLDialogSurface::showDialog()
{
    show();
    int animDuration = 300;

    m_anim = new QPropertyAnimation(m_dialog, "pos", this);
    m_anim->setDuration(animDuration);
    m_anim->setEasingCurve(QEasingCurve::InQuint);
    //m_anim->setEasingCurve(QEasingCurve::OutBack);
    m_anim->setStartValue(QPoint(0, height()));
    m_anim->setEndValue(QPoint(0, 0));

    connect(m_anim, SIGNAL(finished()), SLOT(handleAnimFinished()));
    m_anim->start(QAbstractAnimation::DeleteWhenStopped);
}

void OLDialogSurface::dismissDialog()
{
    if(m_anim) {
        // already have an animation running, use the same simply switch direction
        QAbstractAnimation::Direction newDirection = m_anim->direction()==QAbstractAnimation::Forward ? QAbstractAnimation::Backward : QAbstractAnimation::Forward;
        m_anim->setDirection(newDirection);
    } else {
        //int animDuration = m_dialogtitle->height()+100;
        int animDuration = 300;

        m_anim = new QPropertyAnimation(m_dialog, "pos", this);
        m_anim->setDuration(animDuration);
        m_anim->setEasingCurve(QEasingCurve::InQuint);
        m_anim->setStartValue(m_dialog->pos());
        m_anim->setEndValue(QPoint(0, height()));

        m_anim->start(QAbstractAnimation::DeleteWhenStopped);

        connect(m_anim, SIGNAL(finished()), SLOT(handleAnimFinished()));
    }

    connect(m_anim, SIGNAL(finished()), SLOT(deleteLater()));

    emit dialogClosed((int)this);
}

void OLDialogSurface::handleAnimFinished()
{
    m_anim = 0;
}
